layui.use(['layer', 'form', 'table', 'admin', 'treetable','util'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var admin = layui.admin;
    var treetable = layui.treetable;
    var util = layui.util;

    var Authorization;//请求接口用
    //获取权限方法
    var userInfo = getAuthority();
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getMenuTreeTable();
    }

    // 添加按钮点击事件
    $('#btnAddAuth').click(function () {
        showAddResourceModel();
    });

    // 工具条点击事件
    table.on('tool(tableAuth)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'add') { // 新增
            showAddResourceModel(data);
        }else if (layEvent === 'edit') { // 修改
            showEditResourceModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(data);
        }
    });

    $('#btnRefreshAuth').click(function () {
        getMenuTreeTable();
    });


    //请求菜单树表格
    function getMenuTreeTable() {
        axios.get(systemUrl.permission.permissionTree,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr = [];
                    formatData(data,resArr)
                    renderTable(resArr);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //格式化数据
    function formatData(tdata,resArr) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(value,i){
                resArr.push(value);
                formatData(value.children,resArr);
            });
        }
    }
    //渲染树表格
    function renderTable(treedata) {
        treetable.render({
            treeColIndex: 1,
            treeSpid: -1,
            treeIdName: 'id',
            treePidName: 'parentId',
            elem: '#tableAuth',
            page: false,
            data:treedata,
            treeDefaultClose:true,
            cols: [[
                {type: 'numbers',title: '#'},
                {field: 'name', title: '权限名称', minWidth: 200},
                {field: 'value', title: '权限代码', minWidth: 200},
                {title: '创建日期', minWidth: 200,templet: function (d) {
                        return util.toDateString(d.createTime);
                    }
                },
                {templet: '#tableBarAuth', title: '操作', align: 'center', minWidth: 120}
            ]],
            done: function () {
                layer.closeAll('loading');
            }
        });
    }

    //新增菜单
    function showAddResourceModel(obj) {
        admin.open({
            type: 1,
            title: '新增权限',
            content: $('#AddResourceModel').html(),
            success: function (layero, dIndex) {
                var parent_id  = -1;
                form.render('radio');
                form.render('select');
                if(obj){
                    parentId = obj.id;
                    var req={};
                    req.sort = obj.sort;
                    parent_id = obj.id;
                    form.val('AddResourceForm', req);  // 回显数据
                }
                // 表单提交事件
                form.on('submit(modelSubmitAuth)', function (data) {
                    layer.load(2);
                    var formData = new FormData();
                    formData.append('name',data.field.name);
                    formData.append('parent_id',parent_id);
                    formData.append('sort',data.field.sort);
                    formData.append('value ',data.field.value);

                    axios({
                        method: 'post',
                        url:systemUrl.permission.addPermission,
                        data:formData,
                        headers:{
                            'Authorization':Authorization,
                            'Content-Type':'application/x-www-form-urlencoded'
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getMenuTreeTable();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });

            }
        });
    }

    // 删除菜单
    function doDel(data) {
        layer.confirm('此操作将一并删除其子节点资源，是否继续？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (index) {
            layer.close(index);
            layer.load(2);
            axios({
                method: 'DELETE',
                url:systemUrl.permission.deletePermission+data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getMenuTreeTable();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    //编辑菜单
    function showEditResourceModel(obj){
        admin.open({
            type: 1,
            title: '编辑权限',
            content: $('#editResourceModel').html(),
            success: function (layero, dIndex) {
                form.render('radio');
                form.render('select');

                form.val('editResourceForm', obj);  // 回显数据

                // 表单提交事件
                form.on('submit(modelSubmitAuth)', function (data) {
                    layer.load(2);
                    var formData = new FormData();
                    formData.append('id',obj.id);
                    formData.append('name',data.field.name);
                    formData.append('value',data.field.value);
                    formData.append('sort ',data.field.sort);

                    axios({
                        method: 'put',
                        url:systemUrl.permission.editPermission,
                        data:formData,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                console.log(res)
                                getMenuTreeTable();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });

            }
        });
    }
});